package com.qipay.thirdpart.service.impl;

import com.qipay.thirdpart.config.*;
import com.qipay.thirdpart.service.PayService;
import com.qipay.thirdpart.utils.RequestUtil;
import com.qipay.thirdpart.vo.PayRequest;
import com.qipay.thirdpart.vo.PayResponse;
import com.qipay.utils.NumGeneratorUtils;
import io.jsonwebtoken.lang.Assert;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.TreeMap;

/**
 * Creator: Yao
 * Date:    2017/10/9
 * For:
 * Other:
 */
@Service("TFB8PayServiceImpl")
public class TFB8PayServiceImpl implements PayService {

    private static final Logger logger = LoggerFactory.getLogger(TFB8PayServiceImpl.class);

    @Value("${withdraw.url.single:}")
    private String withdrawSingleUrl;
    @Value("${withdraw.user:}")
    private String withdrawUser;
    @Value("${withdraw.pwd:}")
    private String withdrawPwd;
    @Value("${withdraw.key.public:}")
    private String withdrawPublicKey;
    @Value("${withdraw.key.private:}")
    private String withdrawPrivateKey;

    private final String menoDefault = "提现|代付";

    @Override
    public PayResponse pay(PayRequest req) {

        // check
        Assert.notNull(req);

        // init
        PayResponse res = new PayResponse();

        try {

//            withdrawSingleUrl = "http://apitest.tfb8.com/cgi-bin/v2.0/api_pay_single.cgi";
//            withdrawSingleUrl = "http://api.tfb8.com/cgi-bin/v2.0/api_pay_single.cgi";
//            withdrawUser = "1800046681";
//            withdrawPwd = "12345";
//            withdrawPublicKey = "/data/keys/gczf_rsa_public.pem";
//            withdrawPrivateKey = "/data/keys/dbli_pkcs8_rsa_private_key.pem";

            TreeMap<String, String> paramsMap = new TreeMap<String, String>();
            paramsMap.put(TFB8ParamsEnum.VERSION.getParam(), TFB8VersionEnum.DEFAULT.getVersion());
            paramsMap.put(TFB8ParamsEnum.SP_ID.getParam(), withdrawUser);
            paramsMap.put(TFB8ParamsEnum.SP_SERIAL_NO.getParam(), req.getOutTradeNo());
            paramsMap.put(TFB8ParamsEnum.SP_REQ_TIME.getParam(), req.getOutTradeNo().substring(0, 14));
            paramsMap.put(TFB8ParamsEnum.TRAN_AMT.getParam(), String.valueOf(req.getAmount()));
            paramsMap.put(TFB8ParamsEnum.CUR_TYPE.getParam(), String.valueOf(TFB8CutTypeEnum.RMB.getType()));
            paramsMap.put(TFB8ParamsEnum.PAY_TYPE.getParam(), String.valueOf(TFB8PayTypeEnum.BALANCE.getType()));
            paramsMap.put(TFB8ParamsEnum.ACCT_NAME.getParam(), new String(req.getName().getBytes(), "UTF-8"));
            paramsMap.put(TFB8ParamsEnum.BANK_NAME.getParam(), req.getCardBank());
            paramsMap.put(TFB8ParamsEnum.BANK_BRANCH_NAME.getParam(), req.getCardSubBank());
            paramsMap.put(TFB8ParamsEnum.ACCT_ID.getParam(), req.getCardNo());
            paramsMap.put(TFB8ParamsEnum.ACCT_TYPE.getParam(), String.valueOf(TFB8AcctTypeEnum.DEBIT_CARD.getType()));
            paramsMap.put(TFB8ParamsEnum.MOBILE.getParam(), req.getMobile());
            paramsMap.put(TFB8ParamsEnum.BUSINESS_TYPE.getParam(), TFB8BusinessTypeEnum.BUSINESS_CONTACT.getType());
            paramsMap.put(TFB8ParamsEnum.MEMO.getParam(), new String((StringUtils.isBlank(req.getAttach()) ? menoDefault : req.getAttach()).getBytes(), "UTF-8"));

            res = RequestUtil.request(withdrawSingleUrl, paramsMap, withdrawPwd, withdrawPrivateKey, withdrawPublicKey);
        } catch (Exception e) {

            logger.error(e.getMessage());

            res.setState(ResponseStateEnum.FAIL.getState());
            res.setInfo(e.getMessage());
        }

        return res;
    }

    /****
     * 账号尾号[1]
     *      - responseData=serialno_desc=户名错误&serialno_state=3&sp_serialno=2017101009021171915651546276268&spid=1800046681&tfb_rsptime=20171010090215&tfb_serialno=2017101000030382&sign=920e4bdcbf9fbfcf4967f0caaedc9d97
     *  账号尾号[2]
     *      - <?xml version="1.0" encoding="UTF-8" ?><root><retcode>200001</retcode><retmsg>系统繁忙，请稍后再试!</retmsg><tid>api_pay_single</tid></root>
     * 账号尾号为[!(1|2)]
     *      - responseData=serialno_desc=交易成功&serialno_state=1&sp_serialno=2017101009023465639407555650482&spid=1800046681&tfb_rsptime=20171010090237&tfb_serialno=2017101000030384&sign=5dda83fb446f4cdbf59d3e9a0f3e9bb1
     * @param args
     */
    public static void main(String[] args) {

        // init
        TFB8PayServiceImpl payService = new TFB8PayServiceImpl();
        NumGeneratorUtils generatorUtils = new NumGeneratorUtils();

        // check
        PayResponse res = payService.pay(new PayRequest(1, "招商银行", "观音山支行", "6214835921358501", "姚清居", "158807775955", generatorUtils.generate(), "CP申请提现"));
        System.out.println(res);
    }
}